package com.primaryedu.ui.app.messageboard;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.MessagesBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.BaseAppCompatActivity;
import com.primaryedu.ui.app.nicedialog.BaseNiceDialog;
import com.primaryedu.ui.app.nicedialog.DialogCallBackUtils;
import com.primaryedu.ui.app.nicedialog.DialogSureCallBack;
import com.primaryedu.ui.app.nicedialog.MyCustomDialog;
import com.primaryedu.widget.PullToRefreshView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Thomas on 2018/9/10.
 */

public class MessageboardActivity extends BaseAppCompatActivity implements View.OnClickListener ,DialogSureCallBack {
    private TextView text_look;
    private String urlStr = "";
    private String newId = "";
    List<MessagesBean.DataBean.RowsBean> messageslist;
    private String type = "0";//1，所有留言列表  0，五条展示
    private EditText et_messagewrite;
    private TextView text_right;
    private int page = 1;
    private boolean fistenter = true;

    private MessagesListAdapter adapter;
    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != messageslist && messageslist.size() != 0) {
                        adapter = new MessagesListAdapter(MessageboardActivity.this, messageslist,type);
                        listView.setAdapter(adapter);
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private PullToRefreshView pullToRefreshView;
    private ListView listView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_messageboard);
//        urlStr = getIntent().getStringExtra("urlStr");
//        System.out.println("urlStr==" + urlStr);
    }



    @Override
    protected int BindLayout() {
        return R.layout.activity_messageboard;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void initView() {
        DialogCallBackUtils.setCallBack(this);
        messageslist = new ArrayList<>();
        ((TextView) findViewById(R.id.title)).setText("留言");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.right).setVisibility(View.VISIBLE);
        text_right = (TextView) this.findViewById(R.id.text_right);
        text_right.setText("查看留言");
        text_right.setTextColor(getResources().getColor(R.color.main_messageboard_button));
        text_right.setBackground(null);
        text_right.setOnClickListener(this);
//        findViewById(R.id.bt_messagewrite_submit).setOnClickListener(this);
        //内容
        et_messagewrite = (EditText) findViewById(R.id.et_messagewrite);
        listView = (ListView) this.findViewById(R.id.listView);
    }

    @Override
    protected void initData() {
        getPageListJson(fistenter);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;

        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.text_right:
                intent = new Intent(MessageboardActivity.this, MessagboarddetailsActivity.class);
//                startActivityForResult(intent, REQUESTCODEREPAIR);
                startActivity(intent);
                break;
//            case R.id.bt_messagewrite_submit:
//                if (et_messagewrite.getText().toString().isEmpty()){
//                    showToast("请填写您的留言！");
//                }else {
//                    submitMessages();
//                }
//                break;
            default:
                break;
        }
    }
    public void showdialogSubmit(View view) {
        if (et_messagewrite.getText().toString().isEmpty()) {
            showToast("请填写您的留言！");
            return;
        }
        MyCustomDialog.newInstance("messageboard")
                .setMargin(60)
                .setOutCancel(false)
                .show(getSupportFragmentManager());
    }
    private void submitMessages() {
        if (fistenter) {
            showLoading("发布中...");
        }
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.saveMessages,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("submitmessages==" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            String reason = json.getString("reason");
                            if (result == 1) {
                                showToast("发布留言成功！");
                                et_messagewrite.setText("");
                                messageslist.clear();
                                getPageListJson(false);
                            } else {
                                showToast("发布留言失败！");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("网络访问失败，请检查网络！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("content", et_messagewrite.getText().toString());
                map.put("classId", GlobalData.getClassid(getApplicationContext()));
                map.put("className", GlobalData.getClassname(getApplicationContext()));
                map.put("studentName", GlobalData.getUsername(getApplicationContext()));
                map.put("userId", GlobalData.getUserId(getApplicationContext()));
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    private void getPageListJson(boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getMessages,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("getmessages==" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
//                            String reason = json.getString("reason");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject dataObj = new JSONObject(data);
                                String rows = dataObj.getString("rows");

                                messageslist = new Gson().fromJson(rows,
                                        new TypeToken<List<MessagesBean.DataBean.RowsBean>>() {
                                        }.getType());
                                handler.sendEmptyMessage(1001);
                                System.out.println("getComment=00=" + messageslist.toString());

                            } else {
                                showToast("留言获取失败");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("网络访问失败，请检查网络！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageNo", String.valueOf(page));
                map.put("pageSize", "5");
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void SureClick(String type, BaseNiceDialog dialog) {
        if ("messageboard".equals(type)) {
            submitMessages();
        }
        dialog.dismiss();
    }
}
